import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 缓存配置
const CACHE_CONFIG = {
  // 默认缓存过期时间（5分钟）
  DEFAULT_EXPIRE_TIME: 5 * 60 * 1000,
  // 各数据类型的缓存过期时间配置
  EXPIRE_TIMES: {
    tags: 10 * 60 * 1000,      // 标签缓存10分钟
    categories: 10 * 60 * 1000, // 分类缓存10分钟
    articles: 5 * 60 * 1000,    // 文章缓存5分钟
    personalInfo: 30 * 60 * 1000, // 个人信息缓存30分钟
    recordInfo: 60 * 60 * 1000,   // 备案信息缓存1小时
  }
}

export const useCacheStore = defineStore('cache', () => {
  // 缓存数据存储
  const cacheData = ref({
    tags: {
      data: null,
      timestamp: null,
      loading: false
    },
    categories: {
      data: null,
      timestamp: null,
      loading: false
    },
    articles: {
      data: new Map(), // 使用 Map 存储不同查询条件的文章列表
      timestamp: new Map(),
      loading: new Map()
    },
    personalInfo: {
      data: null,
      timestamp: null,
      loading: false
    },
    recordInfo: {
      data: null,
      timestamp: null,
      loading: false
    }
  })

  // 检查缓存是否过期
  const isCacheExpired = (type, key = 'default') => {
    const expireTime = CACHE_CONFIG.EXPIRE_TIMES[type] || CACHE_CONFIG.DEFAULT_EXPIRE_TIME
    
    if (type === 'articles') {
      const timestamp = cacheData.value[type].timestamp.get(key)
      return !timestamp || (Date.now() - timestamp) > expireTime
    } else {
      const timestamp = cacheData.value[type].timestamp
      return !timestamp || (Date.now() - timestamp) > expireTime
    }
  }

  // 检查缓存是否存在且有效
  const isCacheValid = (type, key = 'default') => {
    if (type === 'articles') {
      return cacheData.value[type].data.has(key) && !isCacheExpired(type, key)
    } else {
      return cacheData.value[type].data !== null && !isCacheExpired(type)
    }
  }

  // 获取缓存数据
  const getCacheData = (type, key = 'default') => {
    if (type === 'articles') {
      return cacheData.value[type].data.get(key)
    } else {
      return cacheData.value[type].data
    }
  }

  // 设置缓存数据
  const setCacheData = (type, data, key = 'default') => {
    const now = Date.now()
    
    if (type === 'articles') {
      cacheData.value[type].data.set(key, data)
      cacheData.value[type].timestamp.set(key, now)
      cacheData.value[type].loading.set(key, false)
    } else {
      cacheData.value[type].data = data
      cacheData.value[type].timestamp = now
      cacheData.value[type].loading = false
    }
  }

  // 设置加载状态
  const setLoading = (type, loading, key = 'default') => {
    if (type === 'articles') {
      cacheData.value[type].loading.set(key, loading)
    } else {
      cacheData.value[type].loading = loading
    }
  }

  // 获取加载状态
  const getLoading = (type, key = 'default') => {
    if (type === 'articles') {
      return cacheData.value[type].loading.get(key) || false
    } else {
      return cacheData.value[type].loading
    }
  }

  // 清除指定类型的缓存
  const clearCache = (type, key = null) => {
    if (type === 'articles') {
      if (key) {
        cacheData.value[type].data.delete(key)
        cacheData.value[type].timestamp.delete(key)
        cacheData.value[type].loading.delete(key)
      } else {
        cacheData.value[type].data.clear()
        cacheData.value[type].timestamp.clear()
        cacheData.value[type].loading.clear()
      }
    } else {
      cacheData.value[type].data = null
      cacheData.value[type].timestamp = null
      cacheData.value[type].loading = false
    }
  }

  // 清除所有缓存
  const clearAllCache = () => {
    Object.keys(cacheData.value).forEach(type => {
      clearCache(type)
    })
  }

  // 清除过期缓存
  const clearExpiredCache = () => {
    Object.keys(cacheData.value).forEach(type => {
      if (type === 'articles') {
        const dataMap = cacheData.value[type].data
        const timestampMap = cacheData.value[type].timestamp
        const loadingMap = cacheData.value[type].loading
        
        for (const [key] of dataMap) {
          if (isCacheExpired(type, key)) {
            dataMap.delete(key)
            timestampMap.delete(key)
            loadingMap.delete(key)
          }
        }
      } else {
        if (isCacheExpired(type)) {
          clearCache(type)
        }
      }
    })
  }

  // 获取缓存统计信息
  const getCacheStats = computed(() => {
    const stats = {}
    
    Object.keys(cacheData.value).forEach(type => {
      if (type === 'articles') {
        stats[type] = {
          count: cacheData.value[type].data.size,
          keys: Array.from(cacheData.value[type].data.keys()),
          loading: Array.from(cacheData.value[type].loading.entries()).filter(([, loading]) => loading).length
        }
      } else {
        stats[type] = {
          hasData: cacheData.value[type].data !== null,
          isExpired: isCacheExpired(type),
          loading: cacheData.value[type].loading,
          timestamp: cacheData.value[type].timestamp
        }
      }
    })
    
    return stats
  })

  // 生成文章缓存的键
  const generateArticleKey = (params = {}) => {
    const { category, tag, page = 1, pageSize = 10, type } = params
    const keyParts = []
    
    if (type) keyParts.push(`type:${type}`)
    if (category) keyParts.push(`category:${category}`)
    if (tag) keyParts.push(`tag:${tag}`)
    keyParts.push(`page:${page}`)
    keyParts.push(`size:${pageSize}`)
    
    return keyParts.join('|') || 'default'
  }

  return {
    // 状态
    cacheData,
    
    // 计算属性
    getCacheStats,
    
    // 方法
    isCacheExpired,
    isCacheValid,
    getCacheData,
    setCacheData,
    setLoading,
    getLoading,
    clearCache,
    clearAllCache,
    clearExpiredCache,
    generateArticleKey,
    
    // 配置
    CACHE_CONFIG
  }
})